package com.peas.fastdfs.service.impl;

import com.peas.fastdfs.entity.QuartzJob;
import com.peas.fastdfs.service.QuartzManagerService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdScheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 任务调度管理实现类
 */
@Service
@Slf4j
public class QuartzManagerServiceImpl implements QuartzManagerService {

    private Scheduler scheduler;

    @Autowired
    private void setScheduler(Scheduler scheduler){
        this.scheduler = scheduler;
    }



    @Override
    public void initJob(QuartzJob job, Class cls) {
        log.info("初始化任务的调度");
        try{

            TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (null == trigger) {
                addQuartzJob(job, cls);
            }
        }catch (Exception e){
            log.error("初始化任务调度异常！ {} ",e.getMessage());
        }
    }

    /**
     * 向任务调度中添加定时任务
     * @param job
     * @param cls
     */
    private void addQuartzJob(QuartzJob job, Class cls) {
        log.info("向任务调度中添加定时任务");
        try{
            //新建一个JobDetail
            JobDetail jobDetail = JobBuilder.newJob(cls)
                    .withIdentity(job.getJobName(), job.getJobGroup()).build();
            //向JobDetail里面添加数据
            jobDetail.getJobDataMap().put(job.getJobName(), job);
            Map<String, Object> jobDataMap = job.getJobDataMap();
            jobDataMap.forEach((s,o)-> jobDetail.getJobDataMap().put(s,o));

            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());

            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup())
                    .withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, trigger);
        }catch (Exception e){
            log.error("向任务调度中添加定时任务异常！ {} ",e.getMessage());
        }

    }

    @Override
    public void runJob(QuartzJob job) {

        log.info("立即运行任务调度中的定时任务");
        try {
            if (null == job) {
                log.info("定时任务信息为空，无法立即运行");
                return;
            }
            JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
            if(null == jobKey){
                log.info("任务调度中不存在[ {} ]定时任务，不予立即运行！",job.getJobName());
                return;
            }
            scheduler.triggerJob(jobKey);
        } catch (Exception e) {
            log.error("立即运行任务调度中的定时任务异常！ {}" , e.getMessage());
        }
    }

    /***
     * 只能修改表达式
     * @param job
     * @param triggerKey
     * @param trigger
     */
    @Override
    public void updateJob(QuartzJob job, TriggerKey triggerKey, CronTrigger trigger) {
        log.info("修改任务调度中的定时任务");
        try {
            if (null == job || null == triggerKey || null == trigger) {
                log.info("修改调度任务参数不正常！");
                return;
            }
            log.info("原始任务表达式: {}" , trigger.getCronExpression());
            log.info("现在任务表达式: {}", job.getCronExpression());
            if (trigger.getCronExpression().equals(job.getCronExpression())) {
                log.info("任务调度表达式一致，不予进行修改！");
                return;
            }
            log.info("任务调度表达式不一致，进行修改");
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            scheduler.rescheduleJob(triggerKey, trigger);
        } catch (Exception e) {
            log.error("修改任务调度中的定时任务异常！ {}" , e.getMessage());
        }

    }

    @Override
    public void pauseJob(QuartzJob job) {

    }

    @Override
    public void resumeJob(QuartzJob job) {

    }

    @Override
    public void deleteJob(QuartzJob job) {
        log.info("删除任务调度中的定时任务");
        try {
            if (null == job) {
                log.info("删除调度任务参数不正常！");
                return;
            }
            JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
            if(null == jobKey){
                log.info("任务调度中不存在[" + job.getJobName() + "]定时任务，不予进行删除！");
                return;
            }
            scheduler.deleteJob(jobKey);
        } catch (Exception e) {
            log.error("删除任务调度中的定时任务异常！" + e.getMessage(), e);
        }
    }

    @Override
    public void deleteJob(TriggerKey triggerKey) {
        log.info("删除任务调度定时器");
        try {
            if(null == triggerKey){
                log.info("停止任务定时器参数不正常，不予进行停止！");
                return;
            }
            log.info("停止任务定时器");
            scheduler.pauseTrigger(triggerKey);
            scheduler.unscheduleJob(triggerKey);
        } catch (Exception e) {
            log.info("删除任务调度定时器异常！" + e.getMessage() ,e);
        }
    }
}
